using System;
using System.Configuration;
using System.IO;
using Config = System.Configuration.Configuration;

namespace Be.Timvw.Framework.Configuration
{
    /// <summary>
    /// Represents a session in which a given configuration file is loaded into the configuration manager.
    /// </summary>
    public class ConfigurationFileSession : IDisposable
    {
        private readonly byte[] originalConfigurationFileContents;
        private bool isDisposed;

        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationFileSession"/> class.
        /// </summary>
        /// <param name="configurationFileName">Name of the configuration file.</param>
        public ConfigurationFileSession(string configurationFileName)
        {
            this.isDisposed = false;

            if(!File.Exists(ConfigurationFile))
            {
                Config cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                cfg.Save(ConfigurationSaveMode.Minimal, true);
            }

            this.originalConfigurationFileContents = File.ReadAllBytes(ConfigurationFile);
            File.WriteAllBytes(ConfigurationFile, File.ReadAllBytes(configurationFileName));

            this.Refresh();
        }

        /// <summary>
        /// Gets the location of the configuration file.
        /// </summary>
        /// <value>The configuration file.</value>
        public static string ConfigurationFile
        {
            get { return AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; }
        }

        #region IDisposable Members

        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        /// <summary>
        /// Loads the configuration file content into the configuration manager.
        /// </summary>
        private void Refresh()
        {
            Config configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            foreach(ConfigurationSection innerConfigurationSection in configuration.Sections)
            {
                ConfigurationManager.RefreshSection(innerConfigurationSection.SectionInformation.SectionName);
            }

            foreach(ConfigurationSectionGroup innerConfigurationSectionGroup in configuration.SectionGroups)
            {
                this.Refresh(innerConfigurationSectionGroup);
            }
        }

        /// <summary>
        /// Loads the configuration section group into the configuration manager.
        /// </summary>
        private void Refresh(ConfigurationSectionGroup configurationSectionGroup)
        {
            foreach(ConfigurationSectionGroup innerConfigurationSectionGroup in configurationSectionGroup.SectionGroups)
            {
                this.Refresh(innerConfigurationSectionGroup);
            }

            foreach(ConfigurationSection innerConfigurationSection in configurationSectionGroup.Sections)
            {
                ConfigurationManager.RefreshSection(innerConfigurationSection.SectionInformation.SectionName);
            }
        }

        /// <summary>
        /// Disposable pattern
        /// </summary>
        /// <param name="isDisposing"></param>
        protected virtual void Dispose(bool isDisposing)
        {
            if(!this.isDisposed)
            {
                if(this.originalConfigurationFileContents != null)
                {
                    File.WriteAllBytes(ConfigurationFile, this.originalConfigurationFileContents);
                }

                if(isDisposing)
                {
                    this.Refresh();
                }

                this.isDisposed = true;
            }
        }
    }
}